package com.eorchis.module.loginauthentication.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.eorchis.constants.RoleConstants;
import com.eorchis.constants.SystemConstants;
import com.eorchis.core.basedao.dao.impl.HibernateAbstractBaseDao;
import com.eorchis.core.basedao.entity.IBaseEntity;
import com.eorchis.core.basedao.query.condition.IQueryCondition;
import com.eorchis.core.basedao.query.condition.builder.IConditionBuilder;
import com.eorchis.core.basedao.query.condition.builder.impl.DefaultQueryConditionBuilder;
import com.eorchis.core.ui.commond.IQueryCommond;
import com.eorchis.module.department.domain.DepartmentUser;
import com.eorchis.module.loginauthentication.dao.ILoginAuthenticationDao;
import com.eorchis.module.loginauthentication.domain.DepartmentUserBean;
import com.eorchis.module.loginauthentication.domain.LoginAuthenticationBean;
import com.eorchis.module.loginauthentication.domain.SysDepSysRoleView;
import com.eorchis.module.loginauthentication.ui.commond.LoginAuthenticationQueryCommond;
import com.eorchis.module.security.cas.domain.Role;
import com.eorchis.module.trainingclass.domain.TrainingClass;
import com.eorchis.module.trainingquestionnaire.ui.commond.QuestionnaireQueryCommond;
import com.eorchis.utils.utils.PropertyUtil;
import sun.misc.BASE64Decoder;

/**
 * 
 * Title: ConfigurationDaoImpl<br>
 * Description: <br>
 * Copyright @ 2011~2015 Goldgov .All rights reserved.<br>
 * 
 * @author GuoL
 * @createDate 2015-8-14
 * @version $Revision: $
 */
@SuppressWarnings({ "unchecked", "restriction" })
@Repository(value = "com.eorchis.module.loginauthentication.dao.impl.LoginAuthenticationDaoImpl")
public class LoginAuthenticationDaoImpl extends HibernateAbstractBaseDao implements ILoginAuthenticationDao {

	@Override
	public Class<? extends IBaseEntity> entityClass() {
		return null;
	}


	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public void queryConditionProcessor(
			IConditionBuilder defaultQueryConditionBuilder,
			IQueryCommond queryCommond) {
	}
	
	/**
	 * 判断是否有这个人员
	 * 
	 * @return
	 * @author GuoL
	 * @date 2015-9-10
	 */
	public LoginAuthenticationBean userLogin(QuestionnaireQueryCommond queryCommond)
	{
		List<LoginAuthenticationBean> resultList = null;
		LoginAuthenticationBean loginAuthentication=null;
		Map<String, Object> params = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select concat(bu.userId,'') as \"userId\" ," +
					" bu.user_name as  \"userNmae\"  "
				+ " from "+SystemConstants.SYSTEM_CODE+"uum_user  bu left join training_class_user tcu on bu.userid=tcu.user_id"
				+ " where tcu.class_id=:classId and (bu.login_id =:userLoginId  or tcu.mobile_telephone=:userLoginId)");
		params.put("userLoginId",  queryCommond.getSearchUserLoginId());
		params.put("classId",  queryCommond.getSearchClassId());

		IConditionBuilder conditionBuilder = new DefaultQueryConditionBuilder();

		conditionBuilder.setBaseQueryString(sql.toString());
		conditionBuilder.setQueryStringType(QueryStringType.SQL);
		conditionBuilder.setResultObject(LoginAuthenticationBean.class);

		IQueryCondition queryCondition = conditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);

		resultList = new ArrayList<LoginAuthenticationBean>();
		resultList = (List<LoginAuthenticationBean>) this.findList(queryCondition);
		
		// 查出对象
		if(PropertyUtil.objectNotEmpty(resultList) && resultList.size()>0  && PropertyUtil.objectNotEmpty(resultList.get(0))){
			loginAuthentication=resultList.get(0);
		}
		return loginAuthentication;
	}

	/**
	 * 判断是否为本班学员
	 * @return
	 * @author LongJZ
	 * @date 2016-2-18
	 */
	@Override
	public boolean isThisClassUser(QuestionnaireQueryCommond queryCommond) {
		List<LoginAuthenticationBean> resultList = null;
		Map<String, Object> params = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select cu.user_id as \"userId\" from TRAINING_CLASS_USER cu where cu.class_id = :classId and cu.user_id = :userId ");
		params.put("classId", queryCommond.getSearchClassId());
		params.put("userId", queryCommond.getSearchUserId());

		IConditionBuilder conditionBuilder = new DefaultQueryConditionBuilder();

		conditionBuilder.setBaseQueryString(sql.toString());
		conditionBuilder.setQueryStringType(QueryStringType.SQL);
		conditionBuilder.setResultObject(LoginAuthenticationBean.class);

		IQueryCondition queryCondition = conditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);

		resultList = new ArrayList<LoginAuthenticationBean>();
		resultList = (List<LoginAuthenticationBean>) this.findList(queryCondition);

		if (PropertyUtil.objectNotEmpty(resultList) && resultList.size() > 0 && PropertyUtil.objectNotEmpty(resultList.get(0)))
			return true;
		else
			return false;
	}
	
	/**
	 * 判断班级评估方式
	 * @author RongSL
	 * @Date 2017-02-14
	 * */
	@Override
	public int isAssessmentMode(QuestionnaireQueryCommond queryCommond){
		String sql=" select tc.class_id from training_class tc left join training_class_course tcc on tc.class_id=tcc.class_id where (tc.class_id=:classId or tcc.class_course_id=:classId) and tc.questionnaire_Method=:method ";
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("classId", queryCommond.getSearchClassId());
		params.put("method", TrainingClass.QUESTIONNAIRE_METHOD_TYPE_N);
		int i=this.executeFind(QueryStringType.SQL, sql, params).size();
		return i;
	}
	
	/**
	 * 判断账号是否存在or判断密码是否错误
	 * @author RongSL
	 * 2018年3月28日
	 * */
	@Override
	public int isExistUser(LoginAuthenticationQueryCommond queryCommond) throws Exception{
		StringBuffer sb=new StringBuffer(" select case u.password when :passwrod then 1 else 2 end from "+SystemConstants.SYSTEM_CODE+"uum_user u where u.LOGIN_ID=:loginID ");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("loginID", queryCommond.getLoginID());
		params.put("passwrod", new String((new BASE64Decoder()).decodeBuffer(queryCommond.getPassword())));
		List<BigInteger> list=(List<BigInteger>) this.executeFind(QueryStringType.SQL, sb.toString(), params);
		if(!list.isEmpty())
			return list.get(0).intValue();
		else
			return 0;
	}

	@Override
	public DepartmentUser findDepartmentUser(LoginAuthenticationQueryCommond queryCommond) throws Exception {
		StringBuffer sb=new StringBuffer(" select t.user as user,t.department as department from com.eorchis.module.department.domain.DepartmentUser t where t.user.loginID=:loginID ");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("loginID", queryCommond.getLoginID());
		List<DepartmentUser> list=(List<DepartmentUser>) this.executeFind(QueryStringType.HQL, sb.toString(), params,DepartmentUser.class);
		return list.get(0);
	}
	
	@Override
	public DepartmentUserBean findDepartmentUserBean(LoginAuthenticationQueryCommond queryCommond) throws Exception {
		StringBuffer sb=new StringBuffer(" select concat(u.userid,'') as \"userId\", concat(ud.depid,'') as \"deptID\", u.active_state as \"activeState\", "
				+ "u.availability_state as \"availabilityState\", u.birthday as \"birthday\", concat(u.duty_level_code,'') as \"dutyLevelCode\", "
				+ "concat(u.folk_code,'') as \"folkCode\", u.guid as \"guid\", u.hierarchy as \"hierarchy\", "
//				+ "u.dangwu as \"dangwu\", u.shiguan as \"shiguan\", u.tongzhan as \"tongzhan\", u.zugong as \"zugong\", "
				+ "concat(u.login_id,'') as \"loginID\", u.mobile_telephone as \"mobileTelephone\", "
				+ "u.officeholding_date as \"officeHoldingDate\", "
//				+ "u.last_operate_time as \"lastOperateTime\", "
				+ "u.order_num as \"orderNum\", "
				+ "u.paper_num as \"paperNum\", u. password as \"password\", u.phone as \"phone\", concat(u.sex_code,'') as \"sexCode\", "
				+ "u.user_name as \"userName\", u.view_state as \"viewState\", ud.admin_level_code as \"adminLevelCode\", "
				+ "ud.depcode as \"deptCode\", ud.depname as \"deptName\", concat(ud.parent_id,'') as \"parentID\", ud.treepath as \"treepath\" "
				+ "from "+SystemConstants.SYSTEM_CODE+"uum_department_user udu "
				+ "inner join "+SystemConstants.SYSTEM_CODE+"uum_user u on udu.userid = u.userid "
				+ "inner join "+SystemConstants.SYSTEM_CODE+"uum_department ud on udu.depid = ud.depid "
				+ "where u.login_id =:loginID ");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("loginID", queryCommond.getLoginID());
		List<DepartmentUserBean> list=(List<DepartmentUserBean>) this.executeFind(QueryStringType.SQL, sb.toString(), params,DepartmentUserBean.class);
		return list.get(0);
	}

	@Override
	public List<SysDepSysRoleView> findUumSysDepRoleView(LoginAuthenticationQueryCommond queryCommond) throws Exception {
		StringBuffer sb=new StringBuffer(" select t.role_id \"roleID\",t.role_code \"roleCode\",t.role_name \"roleName\",t.depname \"depName\","
				+ "t.depid \"depID\",t.parent_id \"parentID\",t.depcode \"depCode\",t.treepath \"treePath\",t.order_num \"orderNum\" "
				+ "from "+SystemConstants.SYSTEM_CODE+"uum_sys_dep_sysrole_grp_view t where t.login_id=:loginID order by t.active_state ");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("loginID", queryCommond.getLoginID());
		List<SysDepSysRoleView> list=(List<SysDepSysRoleView>) this.executeFind(QueryStringType.SQL, sb.toString(), params,SysDepSysRoleView.class);
		return list;
	}

	@Override
	public Role findRole(LoginAuthenticationQueryCommond queryCommond) throws Exception {
		String s="select concat(r.role_id,'') \"roleID\",r.role_name \"RoleName\",r.role_code \"RoleCode\"  from "+SystemConstants.SYSTEM_CODE+"uum_system_role r where r.role_code='"+RoleConstants.ROLE_CODE_XUEYUAN_ADMIN+"'";
		return (Role)(this.executeFind(QueryStringType.SQL, s, null,Role.class).get(0));
	}
}
